<?php
/**
 *	[TWCMS] (C)2012 TongWang Inc.
 *	$Id: tool_rebuild.php 2 2013-04-27 07:14:17Z nanown@qq.com $
 */
class tool_rebuild extends admin{
	function __construct() {
		parent::__construct();
		$this->main();
	}

	function main() {
		if(!empty($_GET['do']) && $_GET['do'] == 'ajax_rebuild') {
			$this->rebuildFor();
		}else{
			include load_tpl(__CLASS__);
		}
	}

	function rebuildFor() {
		$err = 1;
		if(!empty($_POST['doarr']) && is_array($_POST['doarr'])) {
			$err = 0;
			foreach($_POST['doarr'] as $val) {
				if(in_array($val, array('category'))) {
					$func = $val.'Rebuild';
					if(!$this->$func()) $err = 1;
				}
			}
		}
		$msg = empty($err) ? '更新完成' : '更新出错';
		exit('{"err":'.$err.',"msg":"'.$msg.'"}');
	}

	function categoryRebuild() {
		$model = $this->get_model();
		$query = $this->db->query('SELECT cid,mid FROM `'.TW_DBPRE.'category` WHERE mid>2 AND isindex=0');
		$ret = true;
		while($row = $this->db->fetch_array($query)) {			
			$this->db->query('UPDATE `'.TW_DBPRE.'category` SET `count`=(SELECT count(*) FROM `'.TW_DBPRE.$model[$row['mid']].'` WHERE cid='.$row['cid'].') WHERE `cid` ='.$row['cid']) || $ret = false;
		}
		return $ret;
	}

	#获取模型
	function get_model() {
		$query = $this->db->query('SELECT mid,tablename FROM `'.TW_DBPRE.'model`');
		$arr = array();
		while($row = $this->db->fetch_array($query)) {
			$arr[$row['mid']] = $row['tablename'];
		}
		return $arr;
	}
}